#include "pluginmanager.h"

PluginManager::PluginManager(QObject* parent) : QObject(parent) {}

void PluginManager::loadAll(const QString& path) {
    QDir dir(path);
    foreach (QString fileName, dir.entryList(QDir::Files)) {
        loadPlugin(dir.absoluteFilePath(fileName));
    }
}

bool PluginManager::loadPlugin(const QString& path) {
    QPluginLoader* loader = new QPluginLoader(path);
    if (IPlugin* plugin = qobject_cast<IPlugin*>(loader->instance())) {
        m_plugins.insert(plugin->pluginName(), {loader, plugin});
        emit pluginLoaded(plugin->pluginName(), plugin->createUI());
        return true;
    }
    delete loader;
    return false;
}

void PluginManager::unloadPlugin(const QString& name) {
    if (m_plugins.contains(name)) {
        QPluginLoader* loader = m_plugins[name].first;
        IPlugin* plugin = m_plugins[name].second;

        plugin->deleteLater();
        loader->unload();
        delete loader;

        m_plugins.remove(name);
        emit pluginUnloaded(name);
    }
}

IPlugin* PluginManager::getPlugin(const QString& name) const {
    return m_plugins.value(name).second;
}

QStringList PluginManager::loadedPlugins() const {
    return m_plugins.keys();
}
